package com.test.tool.demo.websocket;

import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.security.Principal;

/**
 * @author 小八
 * @date 2022年04月27日10:49
 */
@Service
@RequiredArgsConstructor
public class OnlineStatisticalHandler {

    private final RedisSimpleUtil redisSimpleUtil;

    private final RedissonClient redissonClient;

    //登入状态
    public static final int LOGIN_STATE = 1;
    //离线状态
    public static final int OFFLINE_STATE = 2;

    /**
     * 异步处理消息
     * @param user 用户
     * @param state 状态
     */
    @Async
    public void statisticalOnline(Principal user, int state){
        RLock lock = this.redissonClient.getLock(user.getName());
        lock.lock();
        if(state == LOGIN_STATE){
            redisSimpleUtil.hincr("SOCKET_LOGIN_USERS",user.getName(),1);
            redisSimpleUtil.incr("SOCKET_LOGIN_DEVICE_COUNT",1);
        }else{
            redisSimpleUtil.decr("SOCKET_LOGIN_DEVICE_COUNT",1);
            redisSimpleUtil.hincr("SOCKET_LOGIN_USERS",user.getName(),-1);
            redisSimpleUtil.compareAndDeleteHash("SOCKET_LOGIN_USERS",user.getName(),0);
            //防止服务断了之后再下线的
            redisSimpleUtil.compareAndDeleteHash("SOCKET_LOGIN_USERS",user.getName(),-1);
        }
        lock.unlock();
    }

}
